<template>
    <div class="SHZY-common-layout">
        <div class="SHZY-common-layout-center">
            <el-row class="SHZY-common-search-box" :gutter="16">
                <el-form @submit.native.prevent>
                    <el-col :span="6">
                        <el-form-item label="功能">
                            <el-select v-model="module" placeholder="请选择功能" clearable>
                                <el-option v-for="item in moduleList" :key="item.id" :label="item.fullName"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="关键词">
                            <el-input v-model="keyword" placeholder="请输入关键词查询" clearable @keyup.enter.native="search()" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item>
                            <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading">
                                {{ $t('common.confirmButton') }}</el-button>
                            <el-button icon="el-icon-refresh-right" @click="reset()">{{ $t('common.reset') }}
                            </el-button>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>
            <div class="SHZY-common-layout-main SHZY-flex-main">
                <el-table v-loading="listLoading" :data="list" size='mini' ref="dragTable" :row-key="row => row.index"
                    v-if="refreshTable">
                    <el-table-column type="index" width="50" label="序号" align="center" />
                    <el-table-column prop="fieldName" label="属性名">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.fieldName" placeholder="请输入属性名" />
                        </template>
                    </el-table-column>
                    <!-- <el-table-column prop="field" label="列名">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.field" placeholder="请输入列名" maxlength="50" />
                        </template>
                    </el-table-column> -->
                    <el-table-column prop="dataType" label="类型" width="150">
                        <template slot-scope="scope">
                            <el-select v-model="scope.row.dataType" placeholder="请选择">
                                <el-option v-for="item in options" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="dataLength" label="长度" width="150">
                        <template slot-scope="scope">
                            <!-- <el-input v-model="scope.row.dataLength" placeholder="请输入长度"
                                :disabled="scope.row.dataType !== 'varchar' && scope.row.dataType !== 'decimal'" /> -->
                            <el-input-number v-model="scope.row.dataLength" controls-position="right" :min="1" :max="1000"
                                :disabled="scope.row.dataType !== 'varchar' && scope.row.dataType !== 'decimal'"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="50">
                        <template slot-scope="scope">
                            <el-button class="SHZY-table-delBtn" size="mini" type="text"
                                @click="handleDel(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="table-actions" @click="addHandle()">
                    <el-button type="text" icon="el-icon-plus">新建字段</el-button>
                </div>
            </div>
        </div>
    </div>
</template>
  
<script>
import { mapGetters } from 'vuex'
import { DataModelInfo, DataModelUpdate, DataModelCreate } from '@/api/systemData/dataModel'
export default {
    name: 'systemData-dataForm',
    components: {},
    data() {
        return {
            module: '',
            keyword: '',
            dataForm: {
                table: '',
                tableName: '',
                newTable: ''
            },
            list: [],
            moduleList: [],
            btnLoading: false,
            listLoading: false,
            refreshTable: true,
            options: [
                { label: '字符串', value: 'varchar' },
                { label: '整型', value: 'int' },
                { label: '日期时间', value: 'datetime' },
                { label: '浮点', value: 'decimal' },
                { label: '长整型', value: 'bigint' },
                { label: '文本', value: 'text' }
            ]
        }
    },
    computed: {
        ...mapGetters(['userInfo']),
    },
    created() {
        this.getDictionaryData()
        this.initData()
    },
    methods: {
        getDictionaryData() {
            this.$store.dispatch('base/getDictionaryData', { sort: 'moduleList' }).then((res) => {
                this.moduleList = res
            })
        },
        search() {
            this.getTableData()
        },
        reset() {
            this.keyword = ''
            this.getTableData()
        },
        initData() {

        },
        handleDel(index, row) {
            this.list.splice(index, 1)
        },
        addHandle(row) {
            let index = this.list.length, item = {}
            if (!row) {
                var timestamp = new Date().getTime();
                item = {
                    field: "f" + timestamp + this.userInfo.userAccount, dataType: "varchar", dataLength: 50, allowNull: 1, primaryKey: 0, fieldName: "", index
                }
            } else {
                item = {
                    field: row.field,
                    dataType: row.dataType,
                    dataLength: row.dataLength,
                    allowNull: row.allowNull,
                    fieldName: row.fieldName,
                    index,
                    primaryKey: 0
                }
            }
            this.list.push(item)
        },
        dataFormSubmit() {
            if (!this.list.length) {
                this.$message({
                    message: '请至少添加一个字段',
                    type: 'error',
                    duration: 1000
                })
                return
            }
            if (!this.exist()) return
            let index = this.list.length, item = {}
            item = {
                field: "f_id",
                dataType: "varchar",
                dataLength: 50,
                allowNull: 0,
                fieldName: "主键",
                index,
                primaryKey: 1
            }
            this.list.push(item)
            index = this.list.length;
            item = {
                field: "f_foreignId",
                dataType: "varchar",
                dataLength: 50,
                allowNull: 0,
                fieldName: "外键",
                index,
                primaryKey: 0
            }
            this.list.push(item)
            this.btnLoading = true
            let query = {
                tableFieldList: this.list,
                tableInfo: this.dataForm
            }
            this.dataForm.newTable = "t" + new Date().getTime();
            this.dataForm.tableName = "测试表"

            const formMethod = this.dataForm.table ? DataModelUpdate : DataModelCreate
            formMethod(this.dataBase, query).then((res) => {
                this.$message({
                    message: res.msg,
                    type: 'success',
                    duration: 1500,
                    onClose: () => {
                        this.visible = false
                        this.btnLoading = false
                        this.$emit('close', true)
                    }
                })
            }).catch(() => { this.btnLoading = false })
        },
        exist() {
            let isOk = true;
            //  遍历数组，判断非空
            for (let i = 0; i < this.list.length; i++) {
                const e = this.list[i];
                if (!e.field) {
                    this.$message({
                        showClose: true,
                        message: `第${i + 1}行列名不能为空`,
                        type: 'error',
                        duration: 1000
                    });
                    isOk = false
                    break
                }
                let num = this.list.filter(o => o.field == e.field)
                if (num.length > 1) {
                    this.$message({
                        showClose: true,
                        message: `第${i + 1}行列名'${e.field}'已重复`,
                        type: 'error',
                        duration: 1000
                    });
                    isOk = false
                    break
                }
                if (!e.fieldName) {
                    this.$message({
                        showClose: true,
                        message: `第${i + 1}行属性名不能为空`,
                        type: 'error',
                        duration: 1000
                    });
                    isOk = false
                    break
                }
            }
            return isOk;
        }

    }
}
</script>